/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.distribution.comment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.distribution.comment.dao.*;
import com.yami.shop.distribution.comment.dto.AchievementDataDto;
import com.yami.shop.distribution.comment.dto.DistributionUserAchievementDataDto;
import com.yami.shop.distribution.comment.dto.DistributionUserSimpleDto;
import com.yami.shop.distribution.comment.model.*;
import com.yami.shop.distribution.comment.param.RangeTimeParam;
import com.yami.shop.distribution.comment.param.UpdateDistributionUserParam;
import com.yami.shop.distribution.comment.service.DistributionUserService;
import com.yami.shop.distribution.comment.service.DistributionUserWalletService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@AllArgsConstructor
public class DistributionUserServiceImpl extends ServiceImpl<DistributionUserMapper, DistributionUser> implements DistributionUserService {

    private final DistributionUserMapper distributionUserMapper;

    private final DistributionUserBanMapper distributionUserBanMapper;

    private final DistributionUserBindMapper distributionUserBindMapper;

    private final DistributionAuditingMapper distributionAuditingMapper;

    private final DistributionUserWalletService distributionUserWalletService;

    private final DistributionProdBindMapper distributionProdBindMapper;

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;


    @Override
    @Cacheable(cacheNames = "distribution_user", key = "#shopId + ':' + #userId")
    public DistributionUser getByUserIdAndShopId(String userId, Long shopId) {
        return distributionUserMapper.selectOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getUserId, userId).eq(DistributionUser::getShopId, shopId));
    }

    @Override
    @CacheEvict(cacheNames = "distribution_user", key = "#shopId + ':' + #userId")
    public void removeCacheByUserIdAndShopId(String userId, Long shopId) {

    }

    @Override
    public AchievementDataDto getAchievementDataDtoById(Long id) {
        return distributionUserMapper.getAchievementDataDtoById(id);
    }

    @Override
    public DistributionUserAchievementDataDto getDistributionUserLevelAchievementDataByDistributionUserId(Long distributionUserId) {
        return distributionUserMapper.getLevelDistributionUserAchievementDataByDistributionUserId(distributionUserId);
    }

    @Override
    public IPage<DistributionUser> distributionUserPage(Page page, DistributionUser distributionUser, RangeTimeParam rangeTimeParam
            , String mobile, String parentMobile, Integer sortChange) {
        return distributionUserMapper.distributionUserPage(page, distributionUser, rangeTimeParam, mobile, parentMobile, sortChange);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSelectiveAndInsertDistributionUserBan(UpdateDistributionUserParam param, Long modifier) {
        //创建ban对象，插入数据后修改分销员状态
        DistributionUserBan distributionUserBan = new DistributionUserBan();
        distributionUserBan.setDistributionUserId(param.getDistributionUserId());
        distributionUserBan.setRemarks(param.getRemarks());
        distributionUserBan.setBanReason(param.getBanReason());
        distributionUserBan.setState(param.getState());
        distributionUserBan.setModifier(modifier);
        distributionUserBan.setUpdateTime(new Date());
        distributionUserBanMapper.insert(distributionUserBan);
        DistributionUser distributionUserDb = getById(param.getDistributionUserId());

        // 如果之前是清退状态，现在改成正常状态,恢复以前的没有被抢的绑定用户。
        if (distributionUserDb.getState() == 2 && param.getState() == 1) {
            List<DistributionUserBind> userBindList = distributionUserBindMapper.selectList(new LambdaQueryWrapper<DistributionUserBind>()
                    .eq(DistributionUserBind::getDistributionUserId, param.getDistributionUserId())
                    .eq(DistributionUserBind::getState, -1)
                    .eq(DistributionUserBind::getInvalidReason, 3));
            if(CollectionUtil.isNotEmpty(userBindList)) {
                // 查询出所有的清退原因，没有被抢的用户
                List<String> userIds = distributionUserBindMapper.selectClearUserByDistributionUserId(userBindList);
                if(CollectionUtil.isNotEmpty(userIds)) {
                    // 将没有被抢的，失效的绑定用户设为正常。
                    distributionUserBindMapper.recoveryRelationsByUserId(userIds);
                }
            }
        }

        // 更新分销员状态
        DistributionUser distributionUser = new DistributionUser();
        distributionUser.setDistributionUserId(param.getDistributionUserId());
        distributionUser.setState(param.getState());
        distributionUser.setBindTime(distributionUserDb.getBindTime());
        //如果是清退或封禁
        if (param.getState() == 2 || param.getState() == -1) {
            distributionUser.setStateRecord(param.getState());
            //将绑定的用户设为失效
            distributionUserBindMapper.updateStateAndReasonByDistributionUserId(param.getDistributionUserId(), -1);
            //将商品分享记录设为失效
            distributionProdBindMapper.updateStateByDistributionUserId(param.getDistributionUserId(), -1);
            //判断是否为封禁
            if (param.getState() == -1) {
                //将正在处理中的佣金订单冻结
                distributionUserIncomeMapper.updateStateByDistributionUserId(param.getDistributionUserId(), -1);
            }
        }
        // 如果恢复成正常状态就不需要记录之前的状态了
        if(param.getState() == 1){
            distributionUser.setStateRecord(null);
        }
        distributionUserMapper.updateStatusById(distributionUser);
    }

    @Override
    public IPage<DistributionUser> getDistributionUserAchievementPage(Page page, DistributionUser distributionUser, String userMobile) {
        return distributionUserMapper.getDistributionUserAchievementPage(page, distributionUser, userMobile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerDistributionUser(DistributionUser distributionUser) {

        DistributionUser dbDistributionUser = getByUserIdAndShopId(distributionUser.getUserId(), distributionUser.getShopId());

        // 返回自增id
        Long distributionUserId;

        if (dbDistributionUser == null) {
            //存入分销员数据库
            distributionUserMapper.insert(distributionUser);

            distributionUserId = distributionUser.getDistributionUserId();

            //为这个分销员创建一个钱包
            DistributionUserWallet distributionUserWallet = new DistributionUserWallet();
            distributionUserWallet.setAddupAmount(0.0);
            distributionUserWallet.setSettledAmount(0.0);
            distributionUserWallet.setInvalidAmount(0.0);
            distributionUserWallet.setVersion(0);
            distributionUserWallet.setDistributionUserId(distributionUserId);
            distributionUserWallet.setUnsettledAmount(0.0);
            distributionUserWalletService.save(distributionUserWallet);
        } else {
            dbDistributionUser.setState(0);
            distributionUser.setDistributionUserId(dbDistributionUser.getDistributionUserId());
            distributionUserMapper.updateById(distributionUser);
            distributionUserId = dbDistributionUser.getDistributionUserId();
        }


        //创建申请记录该用户是否为本店分销员
        DistributionAuditing distributionAuditing = new DistributionAuditing();
        distributionAuditing.setAuditingTime(new Date());
        distributionAuditing.setShopId(distributionUser.getShopId());
        distributionAuditing.setDistributionUserId(distributionUserId);
        distributionAuditing.setParentDistributionUserId(distributionUser.getParentId());

        //符合条件，自动通过
        if (Objects.equals(distributionUser.getState(),1)) {
            distributionAuditing.setRemarks("系统判断自动通过审核");
            distributionAuditing.setState(1);
        } else {
            distributionAuditing.setState(0);
        }
        if (dbDistributionUser == null) {
            //存入申请记录
            distributionAuditingMapper.insert(distributionAuditing);
        } else {
            DistributionAuditing dbAuditing = distributionAuditingMapper.selectOne(new LambdaQueryWrapper<DistributionAuditing>().eq(DistributionAuditing::getDistributionUserId, distributionUserId));
            distributionAuditing.setAuditingId(dbAuditing.getAuditingId());
            distributionAuditingMapper.updateById(distributionAuditing);
        }






    }

    @Override
    public IPage<DistributionUserSimpleDto> getDistributionUserSimpleDtoByParentUserIdPage(Page page, Long parentDistributionUserId) {
        return distributionUserMapper.getDistributionUserSimpleDtoByParentUserIdPage(page, parentDistributionUserId);
    }


    @Override
    @Cacheable(cacheNames = "distribution_user_by_card_no", key = "#cardNo")
    public DistributionUser getByCardNo(String cardNo) {
        return distributionUserMapper.selectOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getCardNo, cardNo));
    }

    @Override
    @CacheEvict(cacheNames = "distribution_user_by_card_no", key = "#cardNo")
    public void removeCacheByCardNo(String cardNo) {

    }

    @Override
    public List<DistributionUser> getDistributionUserByIdCardNumberAndUserMobile(String identityCardNumber, String userMobile) {
        return distributionUserMapper.getDistributionUserByIdCardNumberAndUserMobile(identityCardNumber,userMobile);
    }

}
